<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="always" class="box-card">
        <div slot="header" class="clearfix">
          <span v-if="!ID.id">{{ $t("question.title1") }}</span>
          <span v-if="ID.id">{{ $t("question.title2") }}</span>
        </div>
        <div class="text item">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="$t('question.discipline') + ':'"
              prop="subjectID"
            >
              <el-select
                @change="change1"
                v-model="ruleForm.subjectID"
                :placeholder="$t('question.select')"
              >
                <el-option
                  v-for="item in subList"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('question.directory') + ':'"
              prop="catalogID"
            >
              <el-select
                v-model="ruleForm.catalogID"
                :placeholder="$t('question.select')"
              >
                <el-option
                  v-for="item in dir"
                  :key="item.id"
                  :label="item.directoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('question.business') + ':'"
              prop="enterpriseID"
            >
              <el-select
                v-model="ruleForm.enterpriseID"
                :placeholder="$t('question.select')"
              >
                <el-option
                  v-for="item in compList"
                  :key="item.id"
                  :label="item.shortName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('question.city') + ':'" required>
              <el-col class="colssss" :span="4">
                <el-form-item prop="province">
                  <el-select
                    v-model="ruleForm.province"
                    :placeholder="$t('question.select')"
                    class="area"
                    @change="change2"
                  >
                    <el-option
                      v-for="item in allCitys"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item prop="city">
                  <el-select
                    class="area"
                    v-model="ruleForm.city"
                    :placeholder="$t('question.select')"
                  >
                    <el-option
                      v-for="item in cit"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item
              :label="$t('question.direction') + ':'"
              prop="direction"
            >
              <el-select
                v-model="ruleForm.direction"
                :placeholder="$t('question.select')"
              >
                <el-option
                  v-for="item in direction"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('question.questionType') + ':'"
              prop="questionType"
            >
              <el-radio-group
                class="e-radio-group"
                v-model="ruleForm.questionType"
              >
                <el-radio
                  class="e-radio"
                  v-for="item in questionType"
                  :key="item.value"
                  :label="item.value"
                  >{{
                    item.label === "单选"
                      ? $t("question.singleChoice")
                      : item.label === "多选"
                      ? $t("question.multipleChoice")
                      : $t("question.shortAnswer")
                  }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('question.difficulty') + ':'"
              prop="difficulty"
            >
              <el-radio-group
                class="e-radio-group"
                v-model="ruleForm.difficulty"
              >
                <el-radio
                  class="e-radio"
                  v-for="item in difficulty"
                  :key="item.value"
                  :label="item.value"
                  >{{
                    item.label === "简单"
                      ? $t("question.easy")
                      : item.label === "一般"
                      ? $t("question.average")
                      : $t("question.difficult")
                  }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('question.stem') + ':'" prop="question">
              <quill-editor
                class="editor"
                v-model="ruleForm.question"
                @blur="queblur"
              ></quill-editor>
            </el-form-item>
            <!-- 选择 -->
            <el-form-item
              v-if="this.ruleForm.questionType === '3' ? false : true"
              :label="$t('question.options') + ':'"
            >
              <!-- 单选 -->
              <el-radio-group
                v-if="ruleForm.questionType === '1'"
                v-model="Right"
              >
                <!-- v-if="res.test(item.code)" -->
                <template>
                  <el-row v-for="item in single" :key="item.code">
                    <el-radio
                      class="group"
                      :label="item.code"
                      :value="item.isRight"
                      v-if="res1.test(item.code)"
                      >{{ item.code }}:
                    </el-radio>
                    <el-input
                      v-if="res1.test(item.code)"
                      class="eInput"
                      v-model="item.title"
                    >
                    </el-input>
                    <img-uplode v-if="res1.test(item.code)" class="imgUP" />
                  </el-row>
                </template>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group
                v-if="ruleForm.questionType === '2'"
                v-model="moreRight"
              >
                <template>
                  <el-row v-for="item in single" :key="item.code">
                    <el-checkbox
                      class="group"
                      :label="item.code"
                      :value="item.isRight"
                      >{{ item.code }}:</el-checkbox
                    >
                    <el-input class="eInput" v-model="item.title" />
                    <img-uplode />
                  </el-row>
                </template>
              </el-checkbox-group>
              <el-button
                class="elButton"
                type="danger"
                :disabled="ruleForm.questionType === '1'"
                @click="addSelect"
                >{{ $t("question.addOptions") }}</el-button
              >
            </el-form-item>
            <el-form-item :label="$t('question.parsingVideo') + ':'">
              <el-input class="vidInput" v-model="ruleForm.videoURL" />
            </el-form-item>
            <el-form-item
              :label="$t('question.answerParsing') + ':'"
              prop="answer"
            >
              <quill-editor
                class="editor"
                v-model="ruleForm.answer"
                @blur="ansblur"
              ></quill-editor>
            </el-form-item>
            <el-form-item :label="$t('question.questionNotes') + ':'">
              <el-input v-model="ruleForm.remarks" type="textarea"></el-input>
            </el-form-item>
            <el-form-item :label="$t('question.questionLabels') + ':'">
              <el-select
                v-model="ruleForm.tags"
                multiple
                :placeholder="$t('question.select')"
              >
                <el-option
                  v-for="item in tag"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.tagName"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              ><el-button @click="addQues" type="primary">
                {{ ID.id ? $t("question.text2") : $t("question.text1") }}
              </el-button></el-form-item
            >
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { list as subjectApi } from "@/api/hmmm/subjects";
import { list as directApi } from "@/api/hmmm/directorys";
import { list as companiesApi } from "@/api/hmmm/companys";
import { datas, provinces, citys } from "@/api/hmmm/citys";
import {
  direction,
  questionType,
  difficulty,
  single,
} from "@/api/hmmm/constants";
import { list as tagsApi } from "@/api/hmmm/tags";
import { add, detail, update } from "@/api/hmmm/questions";
import ImgUplode from "../components/ImgUplode.vue";
export default {
  data() {
    return {
      ruleForm: {
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        province: "", // 城市
        city: "", // 地区
        direction: "", // 方向
        questionType: "1", // 题型
        difficulty: "1", // 难度
        question: "", // 题干
        options: [], // 选项
        videoURL: "", // 解析视频
        answer: "", // 答案解析
        remarks: "", // 题目备注
        tags: "", // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: "请选择学科", trigger: "change" },
        ],
        catalogID: [
          { required: true, message: "请选择目录", trigger: "change" },
        ],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "change" },
        ],

        province: [
          { required: true, message: "请选择城市", trigger: "change" },
        ],
        city: [{ required: true, message: "请选择地区", trigger: "change" }],
        direction: [
          { required: true, message: "请选择方向", trigger: "change" },
        ],
        questionType: [
          { required: true, message: "请选择题型", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" },
        ],
        question: [
          { required: true, message: "请输入题干", trigger: "change" },
        ],
        answer: [
          { required: true, message: "请输入答案解析", trigger: "change" },
        ],
      },
      subList: [],
      dirList: [],
      compList: [],
      allCitys: [],
      direction: [],
      Single: [],
      single: [],
      questionType,
      difficulty,
      content: "",
      input: "",
      tagsList: [],
      Right: "",
      moreRight: [],
      res1: /^[A-D]$/,
      res2: /^[A-D]$/,
      i: 4,
      ID: { id: "" },
      title: "",
      text: "",
    };
  },
  components: {
    ImgUplode,
  },
  created() {
    this.subject();
    this.direct();
    this.companies();
    this.allCitys = provinces();
    this.direction = direction;
    this.Single = JSON.parse(JSON.stringify(single));
    this.single = JSON.parse(JSON.stringify(this.Single.splice(0, 4)));
    this.tags();
    this.getID();
    this.changeName();
  },
  computed: {
    dir() {
      return this.dirList.filter(
        (item) => item.subjectID === this.ruleForm.subjectID
      );
    },
    cit() {
      return citys(this.ruleForm.province);
    },
    tag() {
      return this.tagsList.filter(
        (item) => item.subjectID === this.ruleForm.subjectID
      );
    },
  },
  methods: {
    change1() {
      this.ruleForm.catalogID = "";
      this.ruleForm.tags = "";
    },
    change2() {
      this.ruleForm.city = "";
    },
    queblur() {
      this.$refs.ruleForm.validateField("question");
    },
    ansblur() {
      this.$refs.ruleForm.validateField("answer");
    },
    changeName() {
      if (this.ID.id) {
        this.title = "试题修改";
        this.text = "确认修改";
      } else {
        this.title = "试题录入";
        this.text = "确认提交";
      }
    },
    addSelect() {
      this.Single = JSON.parse(JSON.stringify(single));
      this.i += 1;
      if (this.i > 10) {
        this.$message.warning("选项已到上线");
        this.i = 10;
      }
      const arr = [];
      this.single.forEach((item) => {
        arr.push(item.title);
      });
      this.single = this.Single.splice(0, this.i);
      let i = 0;
      this.single.forEach((item) => {
        item.title = arr[i];
        i++;
      });
    },
    async subject() {
      const { data } = await subjectApi();
      this.subList = data.items;
    },
    async direct() {
      const { data } = await directApi();
      this.dirList = data.items;
    },
    async companies() {
      const { data } = await companiesApi();
      this.compList = data.items;
    },
    async tags() {
      const { data } = await tagsApi();
      this.tagsList = data.items;
    },
    addQues() {
      // 去掉富文本框自带的标签
      this.ruleForm.question = this.ruleForm.question.replace(/<[^>]+>/g, "");
      this.ruleForm.answer = this.ruleForm.answer.replace(/<[^>]+>/g, "");

      // 单选正确答案处理
      if (this.ruleForm.questionType === "1") {
        this.single.splice(4, 6);
        const arr = ["A", "B", "C", "D"];
        for (let i = 0; i < arr.length; i++) {
          if (this.Right === arr[i]) {
            this.single[i].isRight = true;
          } else {
            this.single[i].isRight = false;
          }
        }
      }
      // 多选正确答案处理
      if (this.ruleForm.questionType === "2") {
        this.single.forEach((item) => {
          if (this.moreRight.includes(item.code)) {
            item.isRight = true;
          } else {
            item.isRight = false;
          }
        });
      }
      this.ruleForm.options = this.single;
      console.log(this.ruleForm.tags);
      if (this.ruleForm.tags !== null && this.ruleForm.tags !== "") {
        this.ruleForm.tags = this.ruleForm.tags.join(",");
      }
      this.$refs.ruleForm.validate(async (flag) => {
        if (!flag) return;
        if (this.ID.id) {
          this.ruleForm.id = +this.ID.id;
          this.ruleForm.options.forEach((item) => {
            item.id = +this.ID.id;
          });
          await update(this.ruleForm);
          this.$router.go(-1);
        } else {
          await add(this.ruleForm);
          this.$router.push("/questions/list");
        }
        this.single = JSON.parse(JSON.stringify(single));
        this.$message.success("恭喜操作成功");
      });
    },
    // 获取id
    async getID() {
      this.ID.id = this.$route.query.id;
      if (this.ID.id) {
        const { data } = await detail(this.ID);
        for (const key in data) {
          if (this.ruleForm[key] || this.ruleForm[key] === "") {
            this.ruleForm[key] = data[key];
          }
        }
        this.ruleForm.creator = "超级管理员";
        this.ruleForm.addDate = data.addDate;
        this.ruleForm.number = data.number;
        this.single = data.options;
        const arr = [];
        this.single
          .filter((item) => item.isRight === 1)
          .forEach((item) => arr.push(item.code));
        // 单选回显
        if (this.ruleForm.questionType === "1") {
          this.Right = arr.join();
        }
        // 多选回显
        if (this.ruleForm.questionType === "2") {
          this.moreRight = arr;
          this.i = this.single.length;
        }
        this.ruleForm.question = data.question;
        this.ruleForm.answer = data.answer;
        if (data.tags !== null && data.tags !== "") {
          this.ruleForm.tags = data.tags.toString().split(",");
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.editor {
  height: 240px;
  overflow: hidden;
  border-bottom: 1px solid #ccc;
}
.ql-container {
  height: 200px !important;
}
.vidInput {
  width: 400px;
}
.elButton {
  display: block;
}
.el-select {
  width: 400px;
}
.area {
  width: 192px;
}
.colssss {
  margin-right: 18px;
  width: 189px;
}
.eInput {
  width: 240px;
  margin: 0 10px 0 10px;
}
.e-radio {
  display: flex;
  align-items: center;
  margin-right: 30px;
  margin-top: 10px;
}
.e-radio-group {
  display: flex;
}
</style>
